<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
<%@ page import="org.wso2.carbon.CarbonConstants" %>
<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
<%@ page import="org.wso2.carbon.bpel.ui.clients.BPELPackageManagementServiceClient" %>
<%@ page import="org.wso2.carbon.bpel.stub.mgt.types.DeployedPackagesPaginated" %>
<%@ page import="org.apache.http.HttpStatus" %>
<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
<%@ page import="org.wso2.carbon.bpel.stub.mgt.types.Package_type0" %>
<%@ page import="org.wso2.carbon.bpel.ui.BpelUIUtil" %>
<%@ page import="org.wso2.carbon.bpel.stub.mgt.types.PackageStatusType" %>
<%@ page import="org.wso2.carbon.bpel.stub.mgt.types.UndeployStatus_type0" %>
<!--
 ~ Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you under the Apache License,
 ~ Version 2.0 (the "License"); you may not use this file except
 ~ in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~    http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,
 ~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND, either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 -->

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>

<%
    response.setHeader("Cache-Control",
            "no-store, max-age=0, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers.
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext =
            (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    String cookie = (String)session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

    BPELPackageManagementServiceClient client;
    DeployedPackagesPaginated packageList = null;
    int numberOfPages = 0;
    int pageNumberInt = 0;

    String pageNumber = request.getParameter("pageNumber");
    String operation = request.getParameter("operation");
    String packageName = request.getParameter("packageName");

    boolean isAuthorizedToManagePackages =
                CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/bpel/packages");
    boolean isAuthorizedToMonitor =
            CarbonUIUtil.isUserAuthorized(request, "/permission/admin/monitor/bpel");

    if (isAuthorizedToManagePackages || isAuthorizedToMonitor ) {
        try{
            client = new BPELPackageManagementServiceClient(cookie, backendServerURL, configContext);
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
            session.setAttribute(CarbonUIMessage.ID, uiMsg);
%>
<jsp:include page="../admin/error.jsp"/>
<%
            return;
        }

        if(isAuthorizedToManagePackages && operation != null && packageName != null &&
           operation.equals("undeploy")) {
            try {
                System.out.println(packageName);
                UndeployStatus_type0 status = client.undeploy(packageName);
                if(status.equals(UndeployStatus_type0.FAILED)) {
                    response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                    CarbonUIMessage uiMsg = new CarbonUIMessage(
                            CarbonUIMessage.ERROR,
                            "BPEL package "+ packageName +" undeployment failed.",
                            null);
                    session.setAttribute(CarbonUIMessage.ID, uiMsg);
%>
<jsp:include page="../admin/error.jsp"/>
<%
                    return;
                }
            } catch (Exception e) {
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
                session.setAttribute(CarbonUIMessage.ID, uiMsg);
%>
<jsp:include page="../admin/error.jsp"/>
<%
                return;
            }

        }

        if (isAuthorizedToMonitor || isAuthorizedToManagePackages) {
            if(pageNumber == null) {
                pageNumber = "0";
            }

            try{
                pageNumberInt = Integer.parseInt(pageNumber);
            } catch (NumberFormatException ignored) {

            }

            try{
                packageList = client.getPaginatedPackageList(pageNumberInt);

                if(packageList != null) {
                    numberOfPages = packageList.getPages();
                } else {
                    numberOfPages = 0;
                }
            } catch (Exception e) {
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
                session.setAttribute(CarbonUIMessage.ID, uiMsg);
%>
<jsp:include page="../admin/error.jsp"/>
<%
                return;
            }
        }
    }
%>
<fmt:bundle basename="org.wso2.carbon.bpel.ui.i18n.Resources">
    <carbon:breadcrumb
            label="bpel.packages"
            resourceBundle="org.wso2.carbon.bpel.ui.i18n.Resources"
            topPage="true"
            request="<%=request%>"/>
    <div id="middle">
        <div id="package-list-main">
            <h2><fmt:message key="bpel.headertext_deployed_packages"/></h2>
            <div id="workArea">
                <div id="package-list">
<%
    if (isAuthorizedToManagePackages || isAuthorizedToMonitor) {
        if(packageList != null && packageList.get_package() != null ) {
%>
                    <carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>"
                      page="package_list.jsp" pageNumberParameterName="pageNumber"
                      resourceBundle="org.wso2.carbon.bpel.ui.i18n.Resources"
                      prevKey="prev" nextKey="next"
                      parameters=""/>
                    <table id="packageListTable" class="styledLeft" width="100%">
                        <thead>
                            <tr>
                                <th><nobr><fmt:message key="bpel.package"/> </nobr></th>
                                <th><nobr><fmt:message key="bpel.package.versions"/> </nobr></th>
                                <!--th><nobr><fmt:message key="status"/> </nobr></th-->
<%
        if (isAuthorizedToManagePackages) {
%>
                                <th><nobr><fmt:message key="actions"/> </nobr></th>
<%
        }
%>
                            </tr>
                        </thead>
                        <tbody>
<%
        for(Package_type0 bpelPackage : packageList.get_package()) {
            if(bpelPackage.getState().equals(PackageStatusType.FAILED)) {
%>
                            <tr>
                                <td><%=bpelPackage.getName()%></td>
                                <td colspan="2" style="color:red;"><%=bpelPackage.getErrorLog()%></td>
                            </tr>
<%
                                } else {
%>
                            <tr>
                                <td><%=bpelPackage.getName()%></td>
                                <!--td><%=bpelPackage.getState().toString()%></td-->
                                <td><%=BpelUIUtil.makeCommaSeparatedListOfPackageVersions(bpelPackage.getVersions().getPackageName())%></td>
<%
                if (isAuthorizedToManagePackages) {
%>
                                <td>
<%
                                    if(bpelPackage.getState().equals(PackageStatusType.DEPLOYED) ||
                                       bpelPackage.getState().equals(PackageStatusType.UPDATED)) {
%>
                                    <a id="<%=bpelPackage.getName()%>" href="<%=BpelUIUtil.getUndeployLink(bpelPackage.getName(), pageNumberInt)%>">Undeploy</a>
                                    <script type="text/javascript">
                                        jQuery('#<%=bpelPackage.getName()%>').click(function(){
                                            function handleYes<%=bpelPackage.getName()%>(){
                                                window.location = jQuery('#<%=bpelPackage.getName()%>').attr('href');   
                                            }
                                            CARBON.showConfirmationDialog(
                                                    "Do you want to undeploy package <%=bpelPackage.getName()%>?",
                                                    handleYes<%=bpelPackage.getName()%>,
                                                    null);
                                            return false;
                                        });
                                    </script>
<%
                    } else {
%>
                                    &nbsp;
<%
                    }
%>
                                </td>
<%
                }
%>
                            </tr>
<%
            }
        }
%>
                        </tbody>
                    </table>
                    <carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>"
                      page="package_list.jsp" pageNumberParameterName="pageNumber"
                      resourceBundle="org.wso2.carbon.bpel.ui.i18n.Resources"
                      prevKey="prev" nextKey="next"
                      parameters=""/>
<%
    } else {
%>
                    <p><fmt:message key="there.are.no.deployed.packages"/></p>
<%
    }
} else {
%>
                    <p><fmt:message key="do.not.have.permission.to.view.bpel.packages"/></p>
<%
}
%>
                </div>
            </div>
        </div>
    </div>
</fmt:bundle>